<template>
  <div id="app">
    <el-button @click="newBook()" type="success" size="large" class="create"
      >Create</el-button
    >
    <el-form
      :model="formData"
      ref="vForm"
      label-position="top"
      label-width="80px"
      size="default"
      @submit.prevent
    >
      <div class="container-wrapper">
        <el-table
          ref="vDataTable"
          :data="formData.dataTable.tableData"
          height="80%"
          :border="true"
          :show-summary="false"
          shadow="always"
          :stripe="true"
          :highlight-current-row="true"
          :cell-style="{ padding: '8px 0 ' }"
        >
          <el-table-column type="index" width="50" fixed="left" align="center"></el-table-column>
          <el-table-column
            prop="id"
            label="ID"
            :sortable="true"
            fixed="left"
            align="center"
            :formatter="formatterValue"
            :show-overflow-tooltip="true"
            :min-width="30"
            ><template #default="scope"
              ><span>{{ scope.row["id"] }}</span></template
            ></el-table-column
          >
          <el-table-column
            prop="title"
            label="Title"
            :fixed="false"
            align="center"
            :formatter="formatterValue"
            :show-overflow-tooltip="true"
            :min-width="200"
            ><template #default="scope"
              ><span>{{ scope.row["title"] }}</span></template
            ></el-table-column
          >
          <el-table-column
            prop="author"
            label="Author"
            :fixed="false"
            align="center"
            :formatter="formatterValue"
            :show-overflow-tooltip="true"
            :min-width="100"
            ><template #default="scope"
              ><span>{{ scope.row["author"] }}</span></template
            ></el-table-column
          >
          <el-table-column
            prop="publication_year"
            label="Publication Year"
            :sortable="true"
            :fixed="false"
            align="center"
            :formatter="formatterValue"
            :show-overflow-tooltip="true"
            :min-width="50"
            ><template #default="scope"
              ><span>{{ scope.row["publication_year"] }}</span></template
            ></el-table-column
          >
          <el-table-column
            prop="isbn"
            label="ISBN"
            :fixed="false"
            align="center"
            :formatter="formatterValue"
            :show-overflow-tooltip="true"
            :min-width="100"
            ><template #default="scope"
              ><span>{{ scope.row["isbn"] }}</span></template
            ></el-table-column
          >
          <el-table-column
            prop="create_time"
            label="Create Time"
            :sortable="true"
            :fixed="false"
            align="center"
            :formatter="formatterValue"
            :show-overflow-tooltip="true"
             :min-width="100"
            ><template #default="scope"
              ><span>{{
                formatterValue(
                  scope.row,
                  formData.dataTable.tableColumns[5],
                  scope.row["create_time"]
                )
              }}</span></template
            >
          </el-table-column>
          <el-table-column
            fixed="right"
            class-name="data-table-buttons-column"
            align="'center'"
            label="Operate"
            :min-width="80"
          >
            <template #default="scope">
              <el-button
                @click="handleOperationButtonClick('edit', scope.$index, scope.row)"
                type="primary"
                size="small"
                :round="false"
                :disabled="false"
                :class="['data-table-edit-button']"
                ><Icon name="el-icon-Edit" color="#fff" /><span>Edit</span></el-button>
              <el-popover trigger="click" :visible="popoverRef[scope.$index].visible" placement="left">
                <p>Are you sure to delete this?</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="small" type="success" @click="popoverRef[scope.$index].visible = false">cancel</el-button>
                  <el-button size="small" type="primary" style="margin-top:8px" @click="handleOperationButtonClick('delete', scope.$index, scope.row)"
                    >confirm</el-button
                  >
                </div>
                <template #reference>
                  <el-button name="delete" type="danger" size="small" @click="popoverRef[scope.$index].visible=true">
                      <Icon name="el-icon-Delete" color="#fff" /><span>Delete</span>
                  </el-button>
                </template>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          style="padding: 15px 0 0 0"
          :current-page="formData.dataTable.pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="formData.dataTable.pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.dataTable.pagination.total"
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
        >
        </el-pagination>
      </div>
    </el-form>
  </div>
</template>
<script>
import {
  defineComponent,
  toRefs,
  reactive,
  getCurrentInstance,
  onMounted
} from "vue";
import { getBooks, deleteBook } from "@/api/book";
export default defineComponent({
  components: {},
  props: {},
  setup() {
    const state = reactive({
      popoverRef:[{visible:false,id:0}],
      formData: {
        dataTable: {
          tableData: [],
          tableColumns: [
            {
              columnId: 1,
              prop: "id",
              label: "ID",
              width: "100",
              show: false,
              align: "left",
              fixed: "left",
              sortable: true,
            },
            {
              columnId: 2,
              show: true,
              prop: "title",
              label: "Title",
              width: "150",
              align: "center",
            },
            {
              columnId: 3,
              prop: "author",
              label: "Author",
              width: "100",
              show: true,
              align: "center",
              formatS: "",
            },
            {
              columnId: 4,
              prop: "publication_year",
              label: "Publication Year",
              width: "80",
              show: true,
              align: "center",
              formatS: "",
              sortable: true,
            },
            {
              columnId: 5,
              prop: "isbn",
              label: "ISBN",
              width: "150",
              show: true,
              align: "center",
              formatS: "",
            },
            {
              columnId: 6,
              prop: "createTime",
              label: "Create Time",
              width: "100",
              show: true,
              align: "center",
              sortable: true,
              formatS: "ymd",
            },
          ],
          pagination: {
            currentPage: 1,
            pageSize: 10,
            total: 0,
          },
        },
      },
    });
    onMounted(() => {
      methods.loadDataTable();
    });
    const methods = {
      loadDataTable() {
        let pagination = state.formData.dataTable.pagination;
        getBooks(pagination.currentPage, pagination.pageSize).then((res) => {
          let data = res.data;
          let popoverRef = [];
          data.tableData.forEach(item => {
              popoverRef.push({visible:false,id:item['id']})
          });
          state.popoverRef = popoverRef
          state.formData.dataTable.tableData = data.tableData;
          state.formData.dataTable.pagination = data.pagination;
        });
      },
      handlePageSizeChange(pageSize) {
        state.formData.dataTable.pagination.currentPage = 1;
        state.formData.dataTable.pagination.pageSize = pageSize;
        methods.loadDataTable();
      },
      handleCurrentPageChange(currentPage) {
        state.formData.dataTable.pagination.currentPage = currentPage;
        methods.loadDataTable();
      },
      handleOperationButtonClick(buttonName, rowIndex, row) {
        if (buttonName == "edit") {
          this.$router.push({
            name: "Detail",
            query: { id: row["id"] },
          });
        } else {
          state.popoverRef[rowIndex].visible = false
          deleteBook(row["id"]).then((res) => {
             if(res.code == 0)
               methods.loadDataTable()
          })
        }
      },
      newBook() {
        this.$router.push({
          name: "Create",
        });
      }
    };
    const instance = getCurrentInstance();
    methods.formatterValue = (row, column, cellValue) => {
      if (!cellValue) {
        return "";
      }
      let v = cellValue;
      let y, m, d;
      if (column.formatS) {
        switch (column.formatS) {
          case "ymd":
            let date = new Date(v);
            y = date.getFullYear();
            m = date.getMonth() + 1;
            m = m < 10 ? "0" + m : m;
            d = date.getDate();
            d = d < 10 ? "0" + d : d;
            return y + "-" + m + "-" + d;
        }
      }
      return cellValue;
    };
    return {
      ...toRefs(state),
      ...methods
    };
  },
});
</script>

<style lang="scss">
.el-input-number.full-width-input,
.el-cascader.full-width-input {
  width: 100% !important;
}

.el-form-item--medium {
  .el-radio {
    line-height: 36px !important;
  }

  .el-rate {
    margin-top: 8px;
  }
}

.el-form-item--small {
  .el-radio {
    line-height: 32px !important;
  }

  .el-rate {
    margin-top: 6px;
  }
}

.el-form-item--mini {
  .el-radio {
    line-height: 28px !important;
  }

  .el-rate {
    margin-top: 4px;
  }
}

.clear-fix:before,
.clear-fix:after {
  display: table;
  content: "";
}

.clear-fix:after {
  clear: both;
}

.float-right {
  float: right;
}
</style>

<style lang="scss" scoped>
div.table-container {
  table.table-layout {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;

    td.table-cell {
      display: table-cell;
      height: 36px;
      border: 1px solid #e1e2e3;
    }
  }
}
.el-button.create {
  margin-bottom: 15px;
}
.static-content-item {
  min-height: 20px;
  display: flex;
  align-items: center;

  :deep(.el-divider--horizontal) {
    margin: 0;
  }
}
</style>
